package com.frozenlab.android.weather.provider;

import com.frozenlab.android.weather.activity.R;
import com.frozenlab.android.weather.activity.SecQWeatherActivity;
import com.frozenlab.android.weather.adapter.WeatherAdapter;
import com.frozenlab.android.weather.helper.WundergroundWeatherHelpher;
import com.frozenlab.android.weather.vo.WeatherVO;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class SecQWeatherWidgetProvider extends AppWidgetProvider {

	private static final String TAG = "SecQWeatherWidgetProvider";
	
	private static final String REFRESH_ACTION = "REFRESH_ACTION";

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int N = appWidgetIds.length;

        // Perform this loop procedure for each App Widget that belongs to this provider
        for (int i=0; i<N; i++) {
            int appWidgetId = appWidgetIds[i];

            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.secqweather_appwidget);

            // Create an Intent to launch SecQWeatherActivity
            Intent intent = new Intent(context, SecQWeatherActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
            views.setOnClickPendingIntent(R.id.widgetLinearLayout, pendingIntent);
            
            // Bind the click intent for the refresh button on the widget
            final Intent refreshIntent = new Intent(context, SecQWeatherWidgetProvider.class);
            refreshIntent.setAction(SecQWeatherWidgetProvider.REFRESH_ACTION);
            final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.refresh, refreshPendingIntent);
    		
            updateCurrentWeather(context);
            
            Log.i(TAG,"On update!");
            // Tell the AppWidgetManager to perform an update on the current app widget
            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
        
        super.onUpdate(context, appWidgetManager, appWidgetIds);
	}


	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "On receive!");
		final String action = intent.getAction();
		if (action.equals(REFRESH_ACTION)) {
			updateCurrentWeather(context);
		}

		super.onReceive(context, intent);
	}
	
	private void updateCurrentWeather(Context context) {
		RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.secqweather_appwidget);	
		
		WeatherVO weatherVO = new WeatherVO();
		
		Log.i(TAG, "Updating widget data");
		
		SharedPreferences preferences = context.getSharedPreferences("weather_preferences", 0);

		String latitude = preferences.getString("latitude", null);
		String longitude = preferences.getString("longitude", null);
		Log.i(TAG, "Latitude ="+latitude +" Longtitude="+longitude);

		/* get weather info */
		WeatherAdapter weatherAdapter = new WeatherAdapter();
		if(latitude != null && isNetworkAvailable(context)){
		weatherVO = weatherAdapter.getWeatherByCoordinate(latitude, longitude);
		}else{
			//Log.e(TAG,"Using old data");
			Toast.makeText(context, "Network error, Please check setting.", Toast.LENGTH_SHORT).show();
			
		}
		/* update to remote views  */
        views.setTextViewText(R.id.Location, weatherVO.getCity());
        views.setTextViewText(R.id.Condition, weatherVO.getConditionText());
        views.setTextViewText(R.id.DateLastUpdate, weatherVO.getConditionDate());
        views.setTextViewText(R.id.Temperature, showTemperature(context, weatherVO.getConditionTemperature()));
        
		if(weatherVO.getConditionCode() != null){
			views.setImageViewResource(R.id.imageWeather, getWeatherImageByCode(weatherVO.getConditionCode()));	
		}
		
		/* Set pending intent */
		AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
		ComponentName component = new ComponentName(context, SecQWeatherWidgetProvider.class);
		int[] arrWidgetID = appWidgetManager.getAppWidgetIds(component);		
		appWidgetManager.updateAppWidget(arrWidgetID, views);		

	}
	
    private String showTemperature(Context context, String temperature){
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    	String temperatureUnit = sharedPreferences.getString("temperatureUnit", "F");
    	
    	if (temperatureUnit.equalsIgnoreCase("F")) {
    		temperature = temperature + "\u00B0" + temperatureUnit;
    	}else{
    		temperature = WundergroundWeatherHelpher.convertFahrenheitToCelcius(temperature);
    		temperature = temperature + "\u00B0" + temperatureUnit;
    	}
    	return temperature;
    }
    
	private int getWeatherImageByCode(String strCode){
    	int imageCode = R.drawable.unknown;
    	
    	if (strCode == null){
    		Log.e(TAG,"Code is null");
    		return imageCode;
    	}
    	
    	return WundergroundWeatherHelpher.weatherImageMap.get(strCode);
    }
	
	/* to check is network available. this part can move to component in future */
	private boolean isNetworkAvailable(Context context) {
	    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
}
